﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CivilleWP7.Civille.Source;
using System.Data.Services.Client;
using CivilleWP7.CivilleDataServiceReference;
using SL.Phone.Federation.Utilities;
using System.Windows.Media.Imaging;

namespace CivilleWP7.Views.Pages
{
    public partial class SelectAuthPage : PhoneApplicationPage
    {
        private bool IsLightTheme;
        public SelectAuthPage()
        {
            InitializeComponent();
            setBackground();
        }
        void checkThemeColor()
        {
            var visibility = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (visibility == Visibility.Visible)
                IsLightTheme = true;
            else
                IsLightTheme = false;
        }
        void setBackground()
        {
            checkThemeColor();
            ImageBrush myBrush = new ImageBrush();
            if (IsLightTheme)
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/Backgroundwhite.jpg",UriKind.Relative));
            else
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/Background.jpg",UriKind.Relative));
            LayoutRoot.Background=myBrush;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SignInControl.RequestSecurityTokenResponseCompleted += new EventHandler<SL.Phone.Federation.Controls.RequestSecurityTokenResponseCompletedEventArgs>(SignInControl_RequestSecurityTokenResponseCompleted);
            SignInControl.GetSecurityToken();
        }

        public static bool IsTokenExpired(long p)
        {
            var epoch = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000000;
            return p < epoch;
        }

        void SignInControl_RequestSecurityTokenResponseCompleted(object sender, SL.Phone.Federation.Controls.RequestSecurityTokenResponseCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string identifier = UserContext.GetCurrentToken();
                if (identifier != null)
                {
                    CivilleDataServiceConnector.SetGetUserParameters(identifier);
                    CivilleDataServiceConnector.GetUserQuery.BeginExecute(OnQueryExecuteCompleted, CivilleDataServiceConnector.GetUserQuery);
                }             
            }
        }
        
        private void OnQueryExecuteCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<CivilleUser> queryEnd = result.AsyncState as DataServiceQuery<CivilleUser>;
                    List<CivilleUser> users = queryEnd.EndExecute(result).ToList();
                    if (users.Count() == 0)
                    {
                        CivilleUser newUser = new CivilleUser();
                        string identifier = UserContext.GetCurrentToken();
                        newUser.UserName = identifier;
                        newUser.FirstName = UserContext.GetName();
                        newUser.Points = 0;
                        CivilleDataServiceConnector.CivilleContext.UsePostTunneling = true;
                        CivilleDataServiceConnector.CivilleContext.AddToCivilleUsers(newUser);
                        CivilleDataServiceConnector.CivilleContext.BeginSaveChanges(SaveChangesOptions.Batch, OnSaveCompleted, CivilleDataServiceConnector.CivilleContext);
                    }
                    else
                    {
                        UserContext.CurrentUser = users.ElementAt(0);
                        if (NavigationService.CanGoBack)
                        {
                            NavigationService.GoBack();
                        }
                    }
                });
        }

        private void OnSaveCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    CivilleEntities context = result.AsyncState as CivilleEntities;
                    try
                    {
                        context.EndSaveChanges(result);
                        CivilleDataServiceConnector.SetGetUserParameters(UserContext.GetCurrentToken());
                        CivilleDataServiceConnector.GetUserQuery.BeginExecute((result2) =>
                        {
                            DataServiceQuery<CivilleUser> queryEnd = result.AsyncState as DataServiceQuery<CivilleUser>;
                            UserContext.CurrentUser = queryEnd.EndExecute(result2).First();
                            if (NavigationService.CanGoBack)
                            {
                                NavigationService.GoBack();
                            }
                        },
                        CivilleDataServiceConnector.GetUserQuery);
                    }
                    catch (NotSupportedException e)
                    {
                        MessageBox.Show("There was a problem with registering you...You should be able to continue using the application but we won't remember you the next time you log in");
                    }
                });
        }
    }
}
